// LoanCalculator.jsx
import { useState, useMemo } from 'react'
import { View, Text, Input, Button, ScrollView } from '@tarojs/components'
import { Popup, Radio, Loading, Toast } from '@taroify/core'
import { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import './index.scss'

export default function LoanCalculator() {
  const [loanAmount, setLoanAmount] = useState('')
  const [periods, setPeriods] = useState('')
  const [annualRate, setAnnualRate] = useState('')
  const [repaymentMethod, setRepaymentMethod] = useState('equalPrincipalAndInterest')
  const [isLoading, setIsLoading] = useState(false)
  const [toastConfig, setToastConfig] = useState({ open: false, message: '' })

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '贷款计算变简单，一键知晓每月还款！理财必备工具💰',
      path: '/pages-dk/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '贷款计算变简单，一键知晓每月还款！理财必备工具💰',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  // 添加临时状态变量存储弹窗中的选择
  const [tempMethod, setTempMethod] = useState('equalPrincipalAndInterest')
  const [tempPeriod, setTempPeriod] = useState('')

  const [showPopup, setShowPopup] = useState(false)
  const [showPeriodPopup, setShowPeriodPopup] = useState(false)
  const [schedules, setSchedules] = useState([])
  const [showForm, setShowForm] = useState(true)
  const [activeTab, setActiveTab] = useState('equalPrincipalAndInterest')

  // 显示Toast提示
  const showToast = (message) => {
    setToastConfig({ open: true, message })
    setTimeout(() => {
      setToastConfig({ open: false, message: '' })
    }, 2000)
  }

  // 生成还款计划
  const generateSchedule = (method, P, r, n) => {
    const monthlyRate = r / 100 / 12
    const schedule = []
    if (method === 'equalPrincipalAndInterest') {
      const mPay = (P * (monthlyRate * Math.pow(1 + monthlyRate, n))) / (Math.pow(1 + monthlyRate, n) - 1)
      let balance = P
      for (let i = 1; i <= n; i++) {
        const interest = balance * monthlyRate
        const principal = mPay - interest
        balance -= principal
        schedule.push({ month: i, payment: mPay, principal, interest })
      }
    } else if (method === 'equalPrincipal') {
      const base = P / n
      let balance = P
      for (let i = 1; i <= n; i++) {
        const interest = balance * monthlyRate
        const mPay = base + interest
        balance -= base
        schedule.push({ month: i, payment: mPay, principal: base, interest })
      }
    } else {
      const totalInterest = P * (r / 100) * (n / 12)
      const mPay = (P + totalInterest) / n
      const base = P / n
      for (let i = 1; i <= n; i++) {
        schedule.push({ month: i, payment: mPay, principal: base, interest: totalInterest / n })
      }
    }
    const totalPayment = schedule.reduce((sum, item) => sum + item.payment, 0)
    const totalInterest = totalPayment - P
    return { method, summary: { totalPayment, principal: P, interest: totalInterest, periods: n }, schedule }
  }

  const handleCalculate = () => {
    // 表单验证
    if (!loanAmount) {
      showToast('请输入贷款金额')
      return
    }

    if (!periods) {
      showToast('请选择贷款期数')
      return
    }

    if (!annualRate) {
      showToast('请输入年利率')
      return
    }

    // 判断输入值是否为有效数字
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(loanAmount)) {
      showToast('贷款金额必须是有效的数字')
      return
    }

    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(annualRate)) {
      showToast('年利率必须是有效的数字')
      return
    }

    const P = parseFloat(loanAmount)
    const n = parseInt(periods, 10)
    const r = parseFloat(annualRate)

    if (Number.isNaN(P) || P <= 0) {
      showToast('贷款金额必须是正数')
      return
    }

    if (Number.isNaN(r) || r <= 0) {
      showToast('年利率必须是正数')
      return
    }

    // 添加loading状态
    setIsLoading(true)

    // 使用setTimeout来模拟异步计算，使UI能显示loading状态
    setTimeout(() => {
      const methods = ['equalPrincipalAndInterest', 'equalPrincipal', 'equalPrincipalAndInterestSame']
      const results = methods.map((m) => generateSchedule(m, P, r, n))
      setSchedules(results)
      setShowPopup(false)
      setShowForm(false)
      setActiveTab(repaymentMethod)
      setIsLoading(false)
    }, 300)
  }

  const methodLabels = {
    equalPrincipalAndInterest: '等额本息',
    equalPrincipal: '等额本金',
    equalPrincipalAndInterestSame: '等本等息'
  }

  // 贷款期限选项
  const periodOptions = [
    { value: '12', label: '1年（12期）' },
    { value: '24', label: '2年（24期）' },
    { value: '36', label: '3年（36期）' },
    { value: '60', label: '5年（60期）' },
    { value: '120', label: '10年（120期）' },
    { value: '240', label: '20年（240期）' },
    { value: '360', label: '30年（360期）' }
  ]

  // 使用useMemo缓存当前选中的还款计划，避免每次渲染都重新计算
  const selectedSchedule = useMemo(() => {
    return schedules.find((item) => item.method === activeTab) || schedules[0]
  }, [schedules, activeTab])

  // 打开还款方式弹窗时，初始化临时变量
  const openMethodPopup = () => {
    setTempMethod(repaymentMethod)
    setShowPopup(true)
  }

  // 打开贷款期数弹窗时，初始化临时变量
  const openPeriodPopup = () => {
    setTempPeriod(periods)
    setShowPeriodPopup(true)
  }

  // 处理还款方式临时选择
  const handleTempMethodChange = (value) => {
    setTempMethod(value)
  }

  // 处理期数临时选择
  const handleTempPeriodChange = (value) => {
    setTempPeriod(value)
  }

  // 确认还款方式选择
  const confirmMethod = () => {
    setRepaymentMethod(tempMethod)
    setShowPopup(false)
  }

  // 确认贷款期数选择
  const confirmPeriod = () => {
    setPeriods(tempPeriod)
    setShowPeriodPopup(false)
  }

  // 取消选择（关闭弹窗不保存）
  const cancelPopup = () => {
    setShowPopup(false)
  }

  const cancelPeriodPopup = () => {
    setShowPeriodPopup(false)
  }

  // 自定义Popup样式类
  const popupClass = {
    root: 'custom-popup',
    mask: 'custom-popup-mask'
  }

  return (
    <View className='calc-container'>
      <View className='header-row'>
        {!showForm && (
          <Button className='btn-back' onClick={() => setShowForm(true)}>
            返回
          </Button>
        )}
        <Text className='calc-title'>贷款计算器</Text>
      </View>

      {showForm ? (
        <>
          <View className='form-section'>
            <View className='calc-field'>
              <Text className='label'>贷款金额 (元)</Text>
              <Input
                className='input'
                type='digit'
                value={loanAmount}
                placeholder='请输入金额'
                onInput={(e) => setLoanAmount(e.detail.value)}
              />
            </View>
            <View className='calc-field' onClick={openPeriodPopup}>
              <Text className='label'>贷款期数</Text>
              <View className='selection'>{periods ? `${periods}期` : '选择'}</View>
            </View>
            <View className='calc-field'>
              <Text className='label'>年利率 (%)</Text>
              <Input
                className='input'
                type='digit'
                value={annualRate}
                placeholder='请输入年利率'
                onInput={(e) => setAnnualRate(e.detail.value)}
              />
            </View>
            <View className='calc-field calc-radio-field' onClick={openMethodPopup}>
              <Text className='label'>还款方式</Text>
              <View className='selection'>{methodLabels[repaymentMethod]}</View>
            </View>
          </View>
          <Button className='btn-calc' onClick={handleCalculate} disabled={isLoading}>
            {isLoading ? (
              <View className='loading-container'>
                <Loading className='btn-loading' type='spinner' color='white' />
                计算中...
              </View>
            ) : (
              '开始计算'
            )}
          </Button>
        </>
      ) : (
        <View className='results-section'>
          <View className='tab-group'>
            {Object.entries(methodLabels).map(([key, label]) => (
              <View
                key={key}
                className={`tab-item ${activeTab === key ? 'active' : ''}`}
                onClick={() => setActiveTab(key)}>
                {label}
              </View>
            ))}
          </View>

          {schedules.length > 0 && (
            <View className='result-block'>
              <View className='summary'>
                <Text>
                  共需还款{' '}
                  {selectedSchedule.summary.totalPayment.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  })}{' '}
                  元
                </Text>
                <Text>
                  本金：
                  {selectedSchedule.summary.principal.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  })}{' '}
                  元
                </Text>
                <Text>
                  利息：
                  {selectedSchedule.summary.interest.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  })}{' '}
                  元
                </Text>
                <Text>总期数：{selectedSchedule.summary.periods} 期</Text>
                <Text>
                  月均还款：
                  {(selectedSchedule.summary.totalPayment / selectedSchedule.summary.periods).toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  })}{' '}
                  元
                </Text>
              </View>
              <View className='schedule'>
                <View className='row header'>
                  <Text>期数</Text>
                  <Text>月供(元)</Text>
                  <Text>本金(元)</Text>
                  <Text>利息(元)</Text>
                </View>
                <ScrollView className='scroll-container' scrollY>
                  {selectedSchedule.schedule.map((i) => (
                    <View key={i.month} className='row'>
                      <Text>第{i.month}期</Text>
                      <Text>
                        {i.payment.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                      </Text>
                      <Text>
                        {i.principal.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                      </Text>
                      <Text>
                        {i.interest.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                      </Text>
                    </View>
                  ))}
                  <View className='safe-area-bottom'></View>
                </ScrollView>
              </View>
            </View>
          )}
        </View>
      )}

      {/* 还款方式选择弹窗 */}
      <Popup
        className='custom-popup'
        classes={popupClass}
        style={{ width: '80%' }}
        open={showPopup}
        position='bottom'
        rounded
        onClose={cancelPopup}>
        <View className='popup-header'>请选择还款方式</View>
        <Radio.Group value={tempMethod} onChange={handleTempMethodChange} direction='vertical'>
          {Object.entries(methodLabels).map(([key, label]) => (
            <Radio key={key} name={key} className='popup-radio'>
              {label}
            </Radio>
          ))}
        </Radio.Group>
        <View className='popup-buttons'>
          <Button className='btn-cancel' onClick={cancelPopup}>
            取消
          </Button>
          <Button className='btn-confirm' onClick={confirmMethod}>
            确定
          </Button>
        </View>
      </Popup>

      {/* 贷款期数选择弹窗 */}
      <Popup
        className='custom-popup'
        classes={popupClass}
        style={{ width: '80%' }}
        open={showPeriodPopup}
        position='bottom'
        rounded
        onClose={cancelPeriodPopup}>
        <View className='popup-header'>请选择贷款期数</View>
        <Radio.Group value={tempPeriod} onChange={handleTempPeriodChange} direction='vertical'>
          {periodOptions.map((option) => (
            <Radio key={option.value} name={option.value} className='popup-radio'>
              {option.label}
            </Radio>
          ))}
        </Radio.Group>
        <View className='popup-buttons'>
          <Button className='btn-cancel' onClick={cancelPeriodPopup}>
            取消
          </Button>
          <Button className='btn-confirm' onClick={confirmPeriod}>
            确定
          </Button>
        </View>
      </Popup>

      {/* Toast 提示 */}
      <Toast open={toastConfig.open} position='middle'>
        {toastConfig.message}
      </Toast>
    </View>
  )
}
